import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Alert,
  ActivityIndicator,
  ScrollView,
} from 'react-native';
import { uploadFileWithChunk } from '../utils/chunkUploader';
import { getApiConfig } from '../config';

export default function UploadTester() {
  const [isUploading, setIsUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [lastUploadResult, setLastUploadResult] = useState<any>(null);

  const testUpload = async () => {
    setIsUploading(true);
    setUploadProgress(0);
    setLastUploadResult(null);

    try {
      // 创建一个测试文件对象
      const testFile = {
        uri: 'file:///test/path/test.jpg', // 模拟文件路径
        name: 'test_image.jpg',
        size: 1024 * 1024, // 1MB
        type: 'image/jpeg',
      };

      console.log('🧪 开始测试上传...');
      console.log('测试文件:', testFile);
      console.log('当前服务器:', getApiConfig().baseURL);

      const result = await uploadFileWithChunk({
        file: testFile,
        onProgress: (percent: number) => {
          setUploadProgress(percent);
          console.log(`📤 上传进度: ${percent}%`);
        },
      });

      setLastUploadResult(result);
      console.log('✅ 测试上传完成:', result);
      
      Alert.alert('测试成功', '文件上传测试完成！');

    } catch (error: any) {
      console.error('❌ 测试上传失败:', error);
      setLastUploadResult({ error: error.message });
      
      Alert.alert('测试失败', `上传测试失败: ${error.message}`);
    } finally {
      setIsUploading(false);
    }
  };

  const testSmallFile = async () => {
    setIsUploading(true);
    setUploadProgress(0);
    setLastUploadResult(null);

    try {
      // 创建一个小的测试文件
      const testFile = {
        uri: 'file:///test/path/small.txt',
        name: 'small_test.txt',
        size: 100, // 100 bytes
        type: 'text/plain',
      };

      console.log('🧪 开始测试小文件上传...');
      console.log('测试文件:', testFile);

      const result = await uploadFileWithChunk({
        file: testFile,
        onProgress: (percent: number) => {
          setUploadProgress(percent);
          console.log(`📤 小文件上传进度: ${percent}%`);
        },
      });

      setLastUploadResult(result);
      console.log('✅ 小文件测试上传完成:', result);
      
      Alert.alert('测试成功', '小文件上传测试完成！');

    } catch (error: any) {
      console.error('❌ 小文件测试上传失败:', error);
      setLastUploadResult({ error: error.message });
      
      Alert.alert('测试失败', `小文件上传测试失败: ${error.message}`);
    } finally {
      setIsUploading(false);
    }
  };

  const clearResults = () => {
    setLastUploadResult(null);
    setUploadProgress(0);
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>📤 上传功能测试</Text>
        <Text style={styles.subtitle}>测试文件上传功能是否正常工作</Text>
      </View>

      <View style={styles.configSection}>
        <Text style={styles.sectionTitle}>当前配置</Text>
        <Text style={styles.configText}>
          服务器: {getApiConfig().baseURL}
        </Text>
        <Text style={styles.configText}>
          超时时间: {getApiConfig().timeout}ms
        </Text>
      </View>

      <View style={styles.testSection}>
        <Text style={styles.sectionTitle}>测试选项</Text>
        
        <TouchableOpacity
          style={[styles.testButton, isUploading && styles.testButtonDisabled]}
          onPress={testUpload}
          disabled={isUploading}
        >
          {isUploading ? (
            <ActivityIndicator color="#fff" />
          ) : (
            <Text style={styles.testButtonText}>🧪 测试标准上传</Text>
          )}
        </TouchableOpacity>

        <TouchableOpacity
          style={[styles.testButton, styles.secondaryButton, isUploading && styles.testButtonDisabled]}
          onPress={testSmallFile}
          disabled={isUploading}
        >
          {isUploading ? (
            <ActivityIndicator color="#fff" />
          ) : (
            <Text style={styles.secondaryButtonText}>🧪 测试小文件上传</Text>
          )}
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.clearButton}
          onPress={clearResults}
        >
          <Text style={styles.clearButtonText}>🗑️ 清除结果</Text>
        </TouchableOpacity>
      </View>

      {isUploading && (
        <View style={styles.progressSection}>
          <Text style={styles.sectionTitle}>上传进度</Text>
          <View style={styles.progressBar}>
            <View 
              style={[styles.progressFill, { width: `${uploadProgress}%` }]} 
            />
          </View>
          <Text style={styles.progressText}>{uploadProgress}%</Text>
        </View>
      )}

      {lastUploadResult && (
        <View style={styles.resultSection}>
          <Text style={styles.sectionTitle}>测试结果</Text>
          
          {lastUploadResult.error ? (
            <View style={styles.errorResult}>
              <Text style={styles.errorIcon}>❌</Text>
              <Text style={styles.errorText}>上传失败</Text>
              <Text style={styles.errorMessage}>{lastUploadResult.error}</Text>
            </View>
          ) : (
            <View style={styles.successResult}>
              <Text style={styles.successIcon}>✅</Text>
              <Text style={styles.successText}>上传成功</Text>
              <Text style={styles.successMessage}>{lastUploadResult.message}</Text>
              {lastUploadResult.data && (
                <Text style={styles.successDetails}>
                  响应数据: {JSON.stringify(lastUploadResult.data, null, 2)}
                </Text>
              )}
            </View>
          )}
        </View>
      )}

      <View style={styles.infoSection}>
        <Text style={styles.sectionTitle}>💡 测试说明</Text>
        <Text style={styles.infoText}>
          • 标准上传测试: 测试1MB文件的正常上传流程{'\n'}
          • 小文件上传测试: 测试100字节文件的快速上传{'\n'}
          • 这些测试使用模拟文件，主要用于验证网络连接和API端点{'\n'}
          • 如果测试失败，请先使用网络诊断工具检查连接{'\n'}
          • 测试结果会显示在下方，包括成功/失败信息和详细错误
        </Text>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    padding: 16,
  },
  header: {
    alignItems: 'center',
    marginBottom: 24,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
    color: '#666',
    textAlign: 'center',
  },
  configSection: {
    backgroundColor: '#fff',
    padding: 16,
    borderRadius: 8,
    marginBottom: 24,
    borderLeftWidth: 4,
    borderLeftColor: '#007AFF',
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
    marginBottom: 16,
  },
  configText: {
    fontSize: 14,
    color: '#666',
    marginBottom: 8,
    fontFamily: 'monospace',
  },
  testSection: {
    backgroundColor: '#fff',
    padding: 16,
    borderRadius: 8,
    marginBottom: 24,
  },
  testButton: {
    backgroundColor: '#007AFF',
    padding: 16,
    borderRadius: 8,
    alignItems: 'center',
    marginBottom: 12,
  },
  testButtonDisabled: {
    backgroundColor: '#ccc',
  },
  testButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
  secondaryButton: {
    backgroundColor: '#34C759',
  },
  secondaryButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
  clearButton: {
    backgroundColor: '#FF3B30',
    padding: 12,
    borderRadius: 8,
    alignItems: 'center',
  },
  clearButtonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '600',
  },
  progressSection: {
    backgroundColor: '#fff',
    padding: 16,
    borderRadius: 8,
    marginBottom: 24,
  },
  progressBar: {
    height: 8,
    backgroundColor: '#e0e0e0',
    borderRadius: 4,
    marginBottom: 8,
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
    backgroundColor: '#007AFF',
    borderRadius: 4,
  },
  progressText: {
    fontSize: 16,
    fontWeight: '600',
    color: '#007AFF',
    textAlign: 'center',
  },
  resultSection: {
    backgroundColor: '#fff',
    padding: 16,
    borderRadius: 8,
    marginBottom: 24,
  },
  errorResult: {
    alignItems: 'center',
    padding: 16,
    backgroundColor: '#FFEBEE',
    borderRadius: 8,
  },
  errorIcon: {
    fontSize: 48,
    marginBottom: 8,
  },
  errorText: {
    fontSize: 18,
    fontWeight: '600',
    color: '#D32F2F',
    marginBottom: 8,
  },
  errorMessage: {
    fontSize: 14,
    color: '#D32F2F',
    textAlign: 'center',
    lineHeight: 20,
  },
  successResult: {
    alignItems: 'center',
    padding: 16,
    backgroundColor: '#E8F5E8',
    borderRadius: 8,
  },
  successIcon: {
    fontSize: 48,
    marginBottom: 8,
  },
  successText: {
    fontSize: 18,
    fontWeight: '600',
    color: '#388E3C',
    marginBottom: 8,
  },
  successMessage: {
    fontSize: 14,
    color: '#388E3C',
    textAlign: 'center',
    marginBottom: 12,
  },
  successDetails: {
    fontSize: 12,
    color: '#666',
    fontFamily: 'monospace',
    textAlign: 'center',
    lineHeight: 16,
  },
  infoSection: {
    backgroundColor: '#E3F2FD',
    padding: 16,
    borderRadius: 8,
    marginBottom: 24,
  },
  infoText: {
    fontSize: 14,
    color: '#1976D2',
    lineHeight: 20,
  },
}); 